import React, { PureComponent } from 'react'
import { Button, Form, Input, Modal, message } from 'antd'

const { Item } = Form

export default class SecretKeyModal extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      loading: false,
      isEdit: false,
      record: {},
    }
    this.formRef = React.createRef()
  }

  openModal = () => {
    this.setState({ visible: true, isEdit: false, record: {} }, () => {
      this.formRef.current.resetFields() // 重置表单
    })
  }

  openEditModal = (record) => {
    this.setState({ visible: true, isEdit: true, record }, () => {
      this.formRef.current.setFieldsValue({
        description: record.description,
      })
    })
  }

  closeModal = () => {
    this.setState({ visible: false })
  }

  onConfirm = () => {
    this.formRef.current.validateFields().then(values => {
      this.setState({ loading: true })
      // 调用父级传入的提交函数
      this.props.onSubmit(values)
          .then(() => {
            this.closeModal()
          })
          .catch((error) => {
            console.error(error)
          })
          .finally(() => {
            this.setState({ loading: false })
          })
    })
  }

  render() {
    const { visible, loading } = this.state

    return (
      <Modal
        title={this.state.isEdit ? "编辑密钥" : "创建密钥"}
        visible={visible}
        onCancel={this.closeModal}
        width={520}
        footer={[
          <Button key="cancel" onClick={this.closeModal}>取消</Button>,
          <Button key="ok" type="primary" loading={loading} onClick={this.onConfirm}>
            确定
          </Button>,
        ]}
      >
        <Form ref={this.formRef} layout="vertical">
          <Item
            label="描述"
            name="description"
            rules={[{ required: true, message: '请输入描述' }]}
          >
            <Input placeholder="请输入密钥描述" />
          </Item>
        </Form>
      </Modal>
    )
  }
}